from __future__ import with_statement
import os
import sys
import urllib2

from distutils import log

from paver.easy import *
import paver.virtual
import paver.svn

if sys.platform in ("win32", "cygwin"):
    platform = "win"
elif sys.platform == "linux2":
    platform = "lin"
else:
    platform = "mac"

XR_BASE = "http://releases.mozilla.org/pub/mozilla.org/xulrunner/releases/%(ver)s/runtimes/"
XR_URL = (XR_BASE + "xulrunner-%(ver)s.en-US.%(plat_ext)s") % {
    "ver": "1.9.0.6",
    "plat_ext": {
        "lin": "linux-i686.tar.bz2",
        "win": "win32.zip",
        "mac": "mac-pkg.dmg",
    }[platform],
}

BT_BUNDLE = "browsertests.pybundle"

options(
    virtualenv=Bunch(
        packages_to_install=["pip"],
        paver_command_line="required"
    ),
)

if platform == "win":
    bin_dir = "Scripts"
else:
    bin_dir = "bin"

for executable in ["pip", "easy_install", "python"]:
    # We need absolute path, because some commands are not invoked from the
    # current directory.
    exec_path = path(bin_dir).joinpath(executable).abspath()
    # Quote the path on Windows to avoid issues if it contains whitespace.
    if platform == "win":
        exec_path = '"%s"' % exec_path
    else:
        if not path(exec_path).exists():
            exec_path = executable
    locals()[executable] =  exec_path

@task
@cmdopts([
    ('version=', 'v', 'Release version')
])
def create_release():
    build_dir = path("browsertests")
    if build_dir.exists():
        build_dir.rmtree()
    paver.svn.checkout("http://browsertests.googlecode.com/svn/trunk/bootstrap",
                       build_dir)
    sh("paver bootstrap", cwd=build_dir)
    if not "version" in options.create_release:
        raise BuildFailure("Missing version parameter")

    sh("%s bundle %s -r requirements.txt" % (pip, BT_BUNDLE), cwd=build_dir)

    import zipfile
    destfile = zipfile.ZipFile("browsertests-%s.zip" % options.create_release.version,
                               "w", zipfile.ZIP_DEFLATED)
    for f in path(build_dir).walk():
        if ".svn" in f.splitall():
            continue
        print f
        destfile.write(f)
    destfile.close()

    build_dir.rmtree()

@task
def required():
    """Install the required packages.

    Installs the requirements set in requirements.txt."""
    # pip fails to install simplejson on Windows.
    # But it works with easy_install...
    sh("%s simplejson" % easy_install)

    has_pil = False
    try:
        import Image
        has_pil = True
    except ImportError, e:
        pass

    if not has_pil:
        if platform == "win":
            # PIL fails to install on Windows. It should be installed manually.
            log.info("You should install PIL from http://www.pythonware.com/products/pil/")
        else:
            sh("%s --find-links http://www.pythonware.com/products/pil/ Imaging" %
               easy_install)

    if path(BT_BUNDLE).exists():
        sh("%s install %s" % (pip, BT_BUNDLE))
    else:
        sh("%s install -U -r requirements.txt" % pip)

    path("reftest_results").mkdir()
    call_task("fetch_xulrunner")

@task
def checkout_tests():
    paver.svn.checkout("http://browsertests.googlecode.com/svn/trunk/tests",
                       "tests")

@task
def fetch_xulrunner():
    if platform == "mac":
        XR_MAC_PATH = "/Library/Frameworks/XUL.framework/Versions/Current/xulrunner-bin"
        if not os.path.exists(XR_MAC_PATH):
            log.info("XULRunner doesn't seem to be installed already.\n\n"
                     "You should download and install the package from %s" %
                     XR_URL)
        else:
            log.info("Found XULRunner at %s." % XR_MAC_PATH)
        return

    p = path("xulrunner")
    if p.exists():
        log.info("xulrunner directory already there, not fetching")
        return

    p.mkdir()
    xr_archive = XR_URL.split("/")[-1]
    dest = p / xr_archive
    log.info("Downloading '%s' to '%s'", XR_URL, dest)
    f = urllib2.urlopen(XR_URL)
    with open(dest, "wb") as output:
        output.write(f.read())
    f.close()
    log.info("download done.")

    if platform == "win":
        try:
            import chromium_utils
        except:
            sys.path.append(path(".") / "src" / "browsertests" /
                            "browsertests" / "third_party")
        from chromium_utils.chromium_utils import ExtractZip
        ExtractZip(dest, p, verbose=False)
    elif platform == "lin":
        p.chdir()
        sh("tar jxf %s" % xr_archive)
    else:
        assert False

@task
def create_sample_settings():
    path("bt_settings.py.sample").copy(
        path("src/browsertestsmodels/browsertests/bt_settings.py"))
    path("settings_local.py.sample").copy(
        path("src/browsertestswebapp/browsertests/settings_local.py"))

@task
def init_db():
    path("src/browsertestswebapp/browsertests").chdir()
    sh("%s manage.py syncdb" % python)
    sh("%s manage.py loaddata useragents specs sections" % python)

@task
def runserver():
    path("src/browsertestswebapp/browsertests").chdir()
    sh("%s manage.py runserver" % python)
